//
//  QRcodeScanViewController.m
//  EquesCat
//
//  Created by Chun Hung Cheung on 2025/4/2.
//

#import "QRcodeScanViewController.h"
#import "WSLNativeScanTool.h"
#import "WSLScanView.h"
#import "VL4BLUViewController.h"
#import "YKEspAPTwoViewController.h"
@interface QRcodeScanViewController ()
@property (nonatomic, strong)WSLNativeScanTool * scanTool;
@property (nonatomic, strong)WSLScanView * scanView;
@end

@implementation QRcodeScanViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.extendedLayoutIncludesOpaqueBars = YES;

   if(@available(iOS 15.0,*)){
     
       UINavigationBarAppearance *barApp = [[UINavigationBarAppearance alloc]init];
       barApp.backgroundColor = [UIColor clearColor];
       barApp.backgroundEffect = nil;
       barApp.shadowColor = nil;
       self.navigationController.navigationBar.scrollEdgeAppearance = nil;
       self.navigationController.navigationBar.standardAppearance = barApp;
    }
   
   
   [self setup];
    
    
    //相机权限
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    // 此应用程序没有被授权访问的照片数据。可能是家长控制权限  用户已经明确否认了这一照片数据的应用程序访问
    if (authStatus ==AVAuthorizationStatusRestricted || authStatus ==AVAuthorizationStatusDenied)
    {
        UIAlertView *alter = [[UIAlertView alloc]initWithTitle:NSLocalizedString(@"Sorry", nil)  message:NSLocalizedString(@"Open photo album permissions", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"cancel", nil) otherButtonTitles:NSLocalizedString(@"Open", nil), nil];
        [alter show];
        return;
    }else{
        
        //输出流视图
        UIView *preview  = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 0)];
        [self.view addSubview:preview];
        
        __weak QRcodeScanViewController *weakSelf = self;
        
        //构建扫描样式视图
        _scanView = [[WSLScanView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 0)];
        _scanView.scanRetangleRect = CGRectMake(60, 120 + [UIDevice dev_navigationFullHeight], (self.view.frame.size.width - 2 * 60),  (self.view.frame.size.width - 2 * 60));
        _scanView.colorAngle = [UIColor orangeColor];
        _scanView.photoframeAngleW = 20;
        _scanView.photoframeAngleH = 20;
        _scanView.photoframeLineW = 2;
        _scanView.isNeedShowRetangle = YES;
        _scanView.colorRetangleLine = [UIColor clearColor];
        _scanView.notRecoginitonArea = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
        _scanView.animationImage = [UIImage imageNamed:@"scan.png"];
        _scanView.flashSwitchBlock = ^(BOOL open) {
            [weakSelf.scanTool openFlashSwitch:open];
        };
        [self.view addSubview:_scanView];
        
        
        //初始化扫描工具
        _scanTool = [[WSLNativeScanTool alloc] initWithPreview:preview andScanFrame:_scanView.scanRetangleRect];
        
        _scanTool.scanFinishedBlock = ^(NSString *scanString) {
            NSLog(@"扫描结果 %@",scanString);
            
            [weakSelf.scanTool sessionStopRunning];
            [weakSelf.scanTool openFlashSwitch:NO];
            
            if ([scanString containsString:@"eques_qr_code:device_type="]) {
                
                NSRange range = [scanString rangeOfString:@"device_type="];
                
                NSRange range4 = [scanString rangeOfString:@"&bind_way="];
                
                NSRange rangetype = NSMakeRange(range.location+range.length,range4.location - range.location - range.length);
                int type =  [[scanString substringWithRange:rangetype] intValue];
                
                NSRange range2 = [scanString rangeOfString:@"bind_way="];
                NSRange way_type = NSMakeRange(range2.location+range2.length, 1);
                int way =  [[scanString substringWithRange:way_type] intValue];
            
                switch (type) {
                
                    case EQUESVL2:
                    case EQUESVL4:
                    case EQUESVM2CP:
                    case EQUESVL5:
                    {
                        
                        if([scanString containsString:@"support_wifi_list=1"] && way == 0){
                            
                            YKEspAPTwoViewController *ap = [[YKEspAPTwoViewController alloc]init];
                            ap.devicetype = type;
                            ap.return_wifi_list = YES;
                            ap.send_ip = [scanString containsString:@"support_static_ip=1"];
                           [weakSelf.navigationController pushViewController:ap animated:YES];
                            
                        }else if([scanString containsString:@"support_wifi_list=1"] && way == 1){
                            
                            VL4BLUViewController *vc = [[VL4BLUViewController alloc]init];
                            vc.devicetype = type;
                            vc.bind_way = 1;
                            vc.send_ip = [scanString containsString:@"support_static_ip=1"];
                           [weakSelf.navigationController pushViewController:vc animated:YES];
                            
                        }

                    }
                        
                        break;
                   

                    default:
                        break;
                }
    
                return;
            }
            
            // http://www.eques.com.cn/app-download.php?share_token=91008689&nickName=5e87fc5b64b9f195ed28fd24097a8183
            
            if ([scanString containsString:@"share_token="]) {
                
                NSArray *array = [scanString componentsSeparatedByString:@"="];
                NSString *mainAccounts = [array lastObject];
                
                NSString *token = array[1];
                
                NSArray *array2 = [token componentsSeparatedByString:@"&"];
                
                
                NSURL *url = [YKBusinessFramework user_accept_share_token:[array2 firstObject]];
                NSLog(@"accept_share_device == %@",url);
                [SVProgressHUD showWithDuration:15];
                
                [AFNHTTPSRequest httpsRequestWithUrl:url errorHint:^(id errorData) {
                    NSLog(@"请求数据失败-->%@",errorData);
                    [SVProgressHUD dismiss];
                  
                } result:^(id data) {
                    NSDictionary *dict = (NSDictionary*)data;
                    NSInteger code = [[dict objectForKey:@"code"] integerValue];
                    [SVProgressHUD dismiss];
                    if (code == 0) {
                         NSLog(@"扫描成功");
                        [SVProgressHUD dismiss];
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"reloadData" object:nil];
                         weakSelf.navigationController.navigationBar.barTintColor = [HexChangeRGB colorWithHexString:@"#f7f7f7"];
                        [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
                        [weakSelf.navigationController popViewControllerAnimated:YES];
                         NSString *nick = [NSString stringWithFormat:@"%@ %@ %@",NSLocalizedString(@"You have successfully connected to the", nil),mainAccounts,NSLocalizedString(@"share intelligent cat's eye", nil)];
                      
                        [SVProgressHUD showSuccessWithStatus:nick duration:3];
                        
                        
                         return;
                        
                    }else if (code == 4407){ // 已经绑定
                        
                       
                         weakSelf.navigationController.navigationBar.barTintColor =[HexChangeRGB colorWithHexString:@"#f7f7f7"];
                        [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
                        [weakSelf.navigationController popViewControllerAnimated:YES];
                         NSString *nick = [NSString stringWithFormat:NSLocalizedString(@"You have successfully connected to the intelligent cat's eye, there is no need to repeat scanning", nil)];
                        [SVProgressHUD showSuccessWithStatus:nick duration:3];
                        return ;
                
                    }else{
                       
                
                        [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"Qr code is invalid, please scan it again", nil) duration:2.0];
                        
                        // Start
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                            
                            [weakSelf.scanTool sessionStartRunning];
                            [weakSelf.scanView startScanAnimation];
                        });
                    }
                }];
                
                
            }
            
            
            
        };
        [self.scanView showFlashSwitch:YES];
        
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            [weakSelf.scanTool sessionStartRunning];
            [weakSelf.scanView startScanAnimation];
        }];
        
    }
    
    
    
}

- (void)setup{
    
     UIButton *backbtn = [UIButton buttonWithType:UIButtonTypeCustom];
     backbtn.frame = CGRectMake(0,0,80,40);
     backbtn.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:16.0f];
     backbtn.contentHorizontalAlignment =  UIControlContentHorizontalAlignmentLeft;
    [backbtn setTitle:NSLocalizedString(@"back", nil) forState:UIControlStateNormal];
    [backbtn setTitleColor:[HexChangeRGB colorWithHexString:@"#ffffff"] forState:UIControlStateNormal];
    [backbtn setImage:[UIImage imageNamed:@"button_back_arrow"] forState:UIControlStateNormal];
    [backbtn addTarget:self action:@selector(selectLeftActionClick) forControlEvents:UIControlEventTouchUpInside];
    [backbtn SG_imagePositionStyle:SGImagePositionStyleDefault spacing:5];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backbtn];
    UIButton *titlebutton   = [UIButton buttonWithType:UIButtonTypeCustom];
    titlebutton.frame = CGRectMake(0,0,60,44);
    [titlebutton setTitle:NSLocalizedString(@"Scan code binding", nil) forState:UIControlStateNormal];
    [titlebutton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
     self.navigationItem.titleView = titlebutton;

}

- (void)selectLeftActionClick
{
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
     self.navigationController.navigationBar.barTintColor = [HexChangeRGB colorWithHexString:@"#f7f7f7"];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
     self.navigationController.navigationBar.barTintColor = WXHColor(25, 23, 26, 0.5);

    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        [_scanTool sessionStartRunning];
        [_scanView startScanAnimation];
    }];
}


- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        [_scanView stopScanAnimation];
        [_scanView finishedHandle];
        [_scanView showFlashSwitch:NO];
        [_scanTool sessionStopRunning];
        [SVProgressHUD dismiss];
    }];
    
   
    
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
     self.navigationController.navigationBar.barTintColor = [HexChangeRGB colorWithHexString:@"#f7f7f7"];
}

@end
